package com.jweb.framework.id;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jweb.framework.core.service.IdCreator;


public abstract class AbstractSequenceFactory implements IdCreator {
    
    protected final Logger logger = LoggerFactory.getLogger(getClass());
    protected String type ;
    private Transform transform ;
    
    private String departId;
    
    public void setType(String t){
        this.type = t ;
    }
    
    public String getType(){
        return this.type ;
    }
    
    public void setFormat(String f) {
        this.transform = Transform.getPattern(f);
    }
    
    public Object create(){
        Object[] obj = create(1,null);
        return obj[0] ;
    }
    
    public Object create(String corpId){
        Object[] obj = create(1,corpId);
        return obj[0] ;
    }
    
    public Object[] create(int i,String corpId) {
        if(this.type == null){
            throw new RuntimeException("you must setType(String) in SequenceFactory.");
        }
        long al[] = internalGenerate(i, corpId);
        if(i==1){
            if(this.transform == null){
                return (new Long[]{new Long(al[0])});
            }
            else {
                return (new String[]{getPattern(al[0] , al[1])});
            }
        }
        if(this.transform == null){
            Long[] along = new Long[i];
            for(int j=0 ; j < i ;j++){
                along[j] = new Long(al[0] + j);
            }
            return along ;
        }
        String as[] = new String[i];
        for(int k=0 ; k<i; k++){
            as[k] = getPattern(al[0] + (long)k , al[1]);
        }
        
        return as ;
    }
    
    private String getPattern(long l , long tim){
        return this.transform.getPattern(this , l , (tim>=0L ? new Date(tim) : new Date()));
    }
    
//    protected abstract long[] internalGenerate(int i);
    protected abstract long[] internalGenerate(int i,String corpId);

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }
    
    
}
